import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    cart:(localStorage.cart)? JSON.parse(localStorage.cart):[],
    result: [],
    check:false,
    js:0,
    liang:0,
    tolist:[],
    list1:[],
    list2:[]
  },


  mutations: {
    //同步list数据
    LIST_AXIOS(state,item) {
     state.tolist=[...item]
     state.lsit1=[...item]
    },
    LIST_AXIOS_ITEM(state,item){
      state.list2=[...item]
    },
    //点击加入购物车
    LB_CART(state,item){
      let aa=true;
      state.cart.map((elent)=>{
        if(elent.item._id==item._id){
          elent.num++
          aa=false
        }
      })
      if(aa){
        state.cart.push({
          item:item,
          num:1
        })
      }
      localStorage.cart=JSON.stringify(state.cart)
    },
    //result状态更新
    changeMy(state,v){
      state.result=v;
      console.log(state.result)
    },
    //check状态更新
    che(state,v){
      state.check=v;
    },
    //判断全选框是否选中
    CART_DL(state){
      if(state.result.length===state.cart.length){
        state.check=true
      }else{
        state.check=false
      }
    },
    //点击全选框全选全不选
    qx(state){
      if(state.check){
        state.result=state.cart
      }else{
        state.result=[]
      }
    },
    //计算价格
    js(state,v){
      let a=0
      let b=0
      state.result.map(item=>{
        a+=item.num*item.item.salePrice*100
        b+=item.num
      })
      state.js=a
      state.liang=b
    },
    // 筛选
    defaul(state){
      state.tolist.sort((a, b) => {
        return b.salePrice - a.salePrice;
      });
    },
    price(state){
      state.tolist.sort((a, b) => {
        return a.salePrice - b.salePrice;
      });
    },
    px(state){
          state.tolist = [];
      state.list1.map((res) =>{
        if(res.size == item){
          state.tolist.push(res);
        }else if(item == "ALL"){
          state.tolist = state.list1
        }
      })
    }
  },


  actions: {
    //使用axios获取数据
    ABC(context){
      axios.get("http://localhost:8080/data2.json").then(res=>{
        context.commit("LIST_AXIOS",res.data.result.list);
      }).catch(err => {
        console.error(err)
      })
    },
    A_B_C(context){
  axios.get("http://localhost:8080/data1.json").then(res=>{
        context.commit("LIST_AXIOS_ITEM",res.data.result.slider);
      }).catch(err => {
        console.error(err)
      })
          },
    //点击加入购物车
    LB_CAR(context,item){
      context.commit("LB_CART",item)
    },

    CART_D(context){
      context.commit("CART_DL");
    }
  },
  modules: {
    
  }
})
